package com.dynamicPlanning;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 *某一个数组中，字符串都成对出现，找出单一的那个。
 */
public class FindSingleElement {
    public static void main(String[] args) {
        String[] strings = new String[]{"a","c","a","d","d","b","c"};
        String singleElement = findSingleElement2(strings);
        System.out.println(singleElement);
    }
    public static String findSingleElement1 (String[] array) {
        // write code here
        ArrayList<String> strs = new ArrayList<>();
        for (String s : array) {
            strs.add(s);
        }
        Iterator<String> iterator = strs.iterator();
        ArrayList<String> strTemp = new ArrayList<>();
        while(iterator.hasNext()){
            String str = iterator.next();
            iterator.remove();
            if (strs.size() == 0 && strTemp.size() == 0){
                return str;
            }
            if(!strs.contains(str)){
                if(!strTemp.contains(str)){
                    return str;
                }
            }
            strTemp.add(str);
        }
        return null;
    }
    public static String findSingleElement2 (String[] array) {
        Arrays.sort(array);
        for (int i = 1; i < array.length; i+=2) {
            if(array[i] != array[i-1]){
                return array[i-1];
            }
            if (i+1 == array.length-1){
                return array[array.length-1];
            }
        }
        throw new RuntimeException("");
    }
}
